package com.base.springboot.starter.mybatisplus.service;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * mybatisplus 填充策略
 *
 * @author yangguan
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String ID_FIELD = "id";
    private static final String CREATE_TIME_FIELD = "createTime";
    private static final String MODIFY_TIME_FIELD = "modifyTime";
    private static final String INSERT_DATE_FIELD = "insertDate";
    private static final String UPDATE_DATE_FIELD = "updateDate";

    // @Autowired
    //private LeafService leafService;

    /**
     * 插入时候的填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(ID_FIELD)) {
            Object id = getFieldValByName(ID_FIELD, metaObject);
            if (Objects.isNull(id)) {
                //TODO yzb
                this.setFieldValByName(ID_FIELD, Long.parseLong("0000000"), metaObject);
            }
        }
        if (metaObject.hasSetter(CREATE_TIME_FIELD)) {
            this.setLocateDateTime(CREATE_TIME_FIELD, metaObject);
        }

        if (metaObject.hasSetter(MODIFY_TIME_FIELD)) {
            this.setFieldValByName(MODIFY_TIME_FIELD, LocalDateTime.now(), metaObject);
        }

        if (metaObject.hasSetter(INSERT_DATE_FIELD)) {
            this.setLocateDateTime(INSERT_DATE_FIELD, metaObject);
        }

        if (metaObject.hasSetter(UPDATE_DATE_FIELD)) {
            this.setFieldValByName(UPDATE_DATE_FIELD, LocalDateTime.now(), metaObject);
        }
    }

    /**
     * 设置时间
     *
     * @param fieldName  字段名称
     * @param metaObject 属性对象
     */
    private void setLocateDateTime(String fieldName, MetaObject metaObject) {
        Object fieldValue = getFieldValByName(fieldName, metaObject);
        if (Objects.isNull(fieldValue)) {
            this.setFieldValByName(fieldName, LocalDateTime.now(), metaObject);
        }
    }

    /**
     * 更新时候的填充策略
     *
     * @param metaObject 属性对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(MODIFY_TIME_FIELD)) {
            this.setFieldValByName(MODIFY_TIME_FIELD, LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasSetter(UPDATE_DATE_FIELD)) {
            this.setFieldValByName(UPDATE_DATE_FIELD, LocalDateTime.now(), metaObject);
        }
    }
}
